package com.next

import grails.converters.JSON
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat
import org.grails.web.util.WebUtils

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class AttachmentController
{

    def fileServerService
    def springSecurityService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond Attachment.list(params), model: [attachmentCount: Attachment.count()]
    }

    def show(Attachment attachment)
    {
        respond attachment
    }

    def create()
    {
        def targetUri = request.getHeader("referer")
        respond new Attachment(params), model: [targetUri: targetUri]
    }

    @Transactional
    def save(Attachment attachment)
    {
        if (attachment == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (attachment.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond attachment.errors, view: 'create'
            return
        }

        attachment.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'attachment.label',
                                                                                        default: 'Attachment'),
                    attachment.id])
                redirect attachment
            }
            '*' { respond attachment, [status: CREATED] }
        }
    }

    def edit(Attachment attachment)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)
        def targetUri = request.getHeader("referer")
        def permission = false

        TeamRole editTeamRole = TeamRole.findByName('Edit')

        if (attachment?.user?.id == user.id)
        {
            permission = true
        }
        else if (params['teamName'])
        {
            def attachmentPermission
            switch (params['teamName'])
            {
            case "contactTeam":
                attachmentPermission = ContactTeam.findByContactAndUser(attachment?.contact, user)?.attachmentPermission
                if (attachmentPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "accountTeam":
                attachmentPermission = AccountTeam.findByAccountAndUser(attachment?.account, user)?.attachmentPermission
                if (attachmentPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "opportunityTeam":
                attachmentPermission = OpportunityTeam.findByOpportunityAndUser(attachment?.opportunity, user)?.attachmentPermission
                if (attachmentPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "campaignTeam":
                attachmentPermission = CampaignTeam.findByCampaignAndUser(attachment?.campaign, user)?.attachmentPermission
                if (attachmentPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "issueTeam":
                attachmentPermission = IssueTeam.findByIssueAndUser(attachment?.issue, user)?.attachmentPermission
                if (attachmentPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "assetTeam":
                attachmentPermission = AssetTeam.findByAssetAndUser(attachment?.asset, user)?.attachmentPermission
                if (attachmentPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            }
        }

        if (permission)
        {
            respond attachment, model: [targetUri: targetUri, user: user]
        }
        else
        {
            flash.message = "没有编辑权限"
            redirect uri: request.getHeader("referer")
        }
    }

    @Transactional
    def update(Attachment attachment)
    {
        if (attachment == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (attachment.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond attachment.errors, view: 'edit'
            return
        }

        attachment.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'attachment.label',
                                                                                        default: 'Attachment'),
                    attachment.id])
                // redirect attachment
                redirect uri: params['targetUri']

            }
            '*' { respond attachment, [status: OK] }
        }
    }

    @Transactional
    def delete(Attachment attachment)
    {
        def attachmentTypeName = params['attachmentTypeName']
        if (attachment == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        attachment.delete flush: true
        // redirect(controller: "opportunity", action: "show", id: attachment?.opportunity?.id)
        // redirect(controller: "attachment", action: "show", params: [id: attachment?.opportunity?.id, attachmentTypeName: attachmentTypeName])
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'attachment.label',
                                                                                        default: 'Attachment'), attachment
                    .id])
                // redirect action: "index", method: "GET"
                redirect uri: request.getHeader("referer")
            }
            '*' { render status: NO_CONTENT }
        }

    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'attachment.label',
                                                                                          default: 'Attachment'),
                    params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def prepareSetDisplayOrder()
    {
        def opportunity = Opportunity.findById(params['opportunity'])
        def attachmentType = AttachmentType.findById(params['attachmentType'])
        def attachment = Attachment.findAll("from Attachment where opportunity.id = ${opportunity?.id} and type.id = ${attachmentType?.id} order by displayOrder,createdDate asc")
        respond opportunity, model: [attachment: attachment, attachmentType: attachmentType], view: 'displayOrder'
    }

    @Transactional
    def setDisplayOrder()
    {
        def list = params['imgIdList[]']
        if (list)
        {
            def attachment
            for (
                int i = 0;
                    i < list.size();
                    i++)
            {
                attachment = Attachment.findById(list[i]?.toInteger())
                attachment.displayOrder = i
                attachment.save flush: true
            }
        }
        render([status: "success"] as JSON)
    }

    @Transactional
    def uploadAvatar(Attachment attachment)
    {
        // 图片参数校验

        def file = request.getFile("file")

        if (file.empty)
        {
            flash.message = message(code: '请选择要上传的文件')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
        def imageExtensionsList = ['jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG']
        def fileExtensionsList = ['pdf', 'doc', 'docx', 'xlsx', 'xls']
        def fileSize = request.getContentLength()
        // if (fileSize > 15728640)
        if (fileSize > 20971520)
        {
            // flash.message = message(code: '文件大小不能超过15M')
            flash.message = message(code: '文件大小不能超过20M')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
        def fileOrgName = file?.getOriginalFilename()
        def fileType = fileOrgName?.split('\\.')[-1]
        fileType = fileType?.toLowerCase()
        if (!(fileType in imageExtensionsList) && !(fileType in fileExtensionsList))
        {
            flash.message = message(code: '文件格式不支持')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }

        Company company = Company.findAll()[0]
        String fileServer = company?.fileServer
        InetAddress address = InetAddress.getLocalHost()
        String hostAddress = address.getHostAddress()
        // 将图片临时存储到 images目录中
        def webrootDir = servletContext.getRealPath("/")
        def code = UUID.randomUUID().toString()
        File fileImage = new File(webrootDir, "images/${code}.${fileType}")
        file.transferTo(fileImage)

        if (fileServer)
        {
            // 上传图片信息
            def param = [:]
            param.put("fileType", fileType)
            // param.put("appSessionId", "b6759ecb-0bb8-4c04-93ab-762cb16d91bc")
            // def fileName = fileServerService.upload(fileImage, param, fileServer)
            def fileUrl = fileServerService.upload(fileImage, param, fileServer)
            def thumbnailUrl = fileServerService.compress(fileImage, param, fileServer)

            // 删除临时文件
            if (fileImage.isFile() && fileImage.exists())
            {
                def flag = fileImage.delete()
            }
            // 存储到文件服务器
            if (fileUrl)
            {
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy")
                SimpleDateFormat sdf2 = new SimpleDateFormat("MM")
                SimpleDateFormat sdf3 = new SimpleDateFormat("dd")
                Date date = new Date()

                def year = sdf1.format(date)
                def month = sdf2.format(date)
                def day = sdf3.format(date)

                attachment.fileName = fileOrgName
                attachment.fileUrl = fileServer + "/static/images/${year}/${month}/${day}/${fileUrl}.${fileType}"
                if (thumbnailUrl)
                {
                    attachment.thumbnailUrl = fileServer + "/static/images/${year}/${month}/${day}/${thumbnailUrl}.${fileType}"
                }
            }
            else
            {
                flash.message = message(code: '调用上传文件服务失败，请稍后重试')
                respond attachment, model: [targetUri: params['targetUri']], view: 'create'
                return
            }
        }
        else
        {
            attachment.fileName = fileOrgName
            // attachment.fileUrl = "http://crm.combine-tech.cn/static/images/${code}.${fileType}"
            attachment.fileUrl = WebUtils.retrieveGrailsWebRequest().getBaseUrl() + "/static/images/${code}.${fileType}"
        }
        attachment.description = fileOrgName?.split('\\.')[0]
        def o = [:]
        def files = []
        def sfile = [:]
        if (fileType in imageExtensionsList)
        {
            sfile['thumbnailUrl'] = attachment.fileUrl
        }
        else
        {
            sfile['thumbnailUrl'] = ''
        }
        sfile['name'] = fileOrgName
        files.add(sfile)
        o['files'] = files
        if (attachment.validate())
        {
            attachment.save flush: true
            render o as JSON
        }
        else
        {
            flash.message = message(code: '文件上传失败，请稍后重试')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
    }

}
